import React, {useState, useRef} from 'react';
import {PlusOutlined} from '@ant-design/icons';
import {ProTable, ActionType, ProColumns} from '@ant-design/pro-components';
import {Button, Modal, Form, Input, Select, message, Image} from 'antd';
import {searchUsers, createUser, changeRole,} from '@/services/ant-design-pro/api';
import {FALLBACK_LOGO} from '@/constant';


export const waitTimePromise = async (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};
export const waitTime = async (time: number = 100) => {
  await waitTimePromise(time);
};

const UserManage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isRoleModalVisible, setIsRoleModalVisible] = useState(false); // 修改用户权限模态框
  const [getUserInfo, setUserInfo] = useState<API.changeUserRoleParams | null>(null);
  const [form] = Form.useForm();

  const showRoleModal = (record: API.changeUserRoleParams) => {
    setUserInfo(record);
    // @ts-ignore
    setIsRoleModalVisible(true);
    form.setFieldsValue({userRole: record.userRole}); // 设置表单的初始值
  };

  const columns: ProColumns<API.CurrentUser>[] = [
    {
      dataIndex: 'id',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '用户名',
      dataIndex: 'userName',//返回数据对象属性
      copyable: true,//是否允许复制
      //ellipsis: true,//是否允许分页
    },
    {
      title: '用户账户',
      dataIndex: 'userAccount',//返回数据对象属性
      copyable: true,//是否允许复制
    },
    {
      title: '头像',
      dataIndex: 'avatarUrl',//返回数据对象属性
      render: (_, record) => (
        <div>
          <Image src={record.avatarUrl || FALLBACK_LOGO} width={60} height={40}
                 fallback={FALLBACK_LOGO}
          />
        </div>
      ),
      copyable: true,//是否允许复制
    },
    {
      title: '性别',
      dataIndex: 'gender',
      render: (dom: React.ReactNode, entity: { gender: number }) => {
        if (entity.gender === 0) {
          return '男';
        }
        if (entity.gender === 1) {
          return '女';
        }
        return dom; // 如果数据不是 0 或 1，则返回默认内容
      },
    },
    {
      title: '邮箱',
      dataIndex: 'email',//返回数据对象属性
      copyable: true,//是否允许复制
    },

    {
      title: '状态',
      dataIndex: 'userStatus',//返回数据对象属性
    },
    {
      title: '基地编号',
      dataIndex: 'planetCode',//返回数据对象属性
    },
    {
      title: '角色',
      dataIndex: 'userRole',//返回数据对象属性
      render: (_, record) => (
        <a onClick={() => showRoleModal(record)}>
          {record.userRole === 1 ? '管理员' : record.userRole === 2 ? 'VIP' : '普通用户'}
        </a>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',//返回数据对象属性
      valueType: 'date',
      sorter: true,
      hideInSearch: true,
    },

  ];


  async function handleSubmitCreateUser() {
    try {
      const values = await form.validateFields();
      console.log("参数values1：", values);
      const response = await createUser(values);
      if (response) {
        const defaultLoginSuccessMessage = '新增成功！';
        message.success(defaultLoginSuccessMessage);
        setIsModalVisible(false);
        actionRef.current?.reload();
      }
    } catch (error) {
      message.error('用户创建失败');
    }
  }

  async function handleSubmitChangeUserRole() {
    try {
      if (getUserInfo) {//这里判断空值，是因为初始化getUserInfo参数的时候定义的为null，这里必须判断一下。虽然userAccount不存在空值。
        const { userAccount  } = getUserInfo;
        const values = await form.validateFields();
        const { userRole } = values;

        // 调用 changeRole API 更新用户角色
        const response = await changeRole({userAccount, userRole});
        if (response) {
          actionRef.current?.reload(); // 刷新表格
          message.success('权限更新成功！');
          setIsRoleModalVisible(false); // 关闭模态框
        } else {
          message.error('权限更新失败');
        }
      }
    } catch (error) {
      message.error('操作失败，请重试');
    }
  }


  // @ts-ignore
  return (
    <div id='userManage'>
      <ProTable<API.CurrentUser>
        columns={columns}
        actionRef={actionRef}
        cardBordered
        // @ts-ignore
        request={async (params, sort, filter) => {
          // console.log(sort, filter);
          await waitTime(200);

          const userList = await searchUsers();
          return {
            data: userList
          }
        }}
        editable={{
          type: 'multiple',
        }}
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
          defaultValue: {
            option: {fixed: 'right', disable: true},
          },
          onChange(value) {
            console.log('value: ', value);
          },
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        options={{
          setting: {
            // listsHeight: 400,
          },
        }}
        form={{
          // 由于配置了 transform，提交的参数与定义的不同这里需要转化一下
          syncToUrl: (values, type) => {
            if (type === 'get') {
              return {
                ...values,
                created_at: [values.startTime, values.endTime],
              };
            }
            return values;
          },
        }}
        pagination={{
          pageSize: 5,
          // onChange: (page) => console.log(page),
        }}
        dateFormatter="string"
        headerTitle="高级表格"
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined/>}
            onClick={() => setIsModalVisible(true)}
            type="primary"
          >
            新建
          </Button>,
        ]}
      />
      <Modal
        title="新建用户"
        visible={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        onOk={async () => {
          await handleSubmitCreateUser();
        }}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="userAccount"
            label="用户账户"
            rules={[{required: true, message: '请输入用户账户'}]}
          >
            <Input placeholder="请输入用户账户"/>
          </Form.Item>
          <Form.Item
            name="userPassword"
            label="密码"
            rules={[{required: true, message: '请输入密码'}]}
          >
            <Input.Password placeholder="请输入密码"/>
          </Form.Item>
          <Form.Item
            name="checkPassword"
            label="校验密码"
            rules={[{required: true, message: '请输入校验密码'}]}
          >
            <Input.Password placeholder="请输入校验密码"/>
          </Form.Item>
          <Form.Item
            name="planetCode"
            label="基地编号"
            rules={[{required: true, message: '请输入编号'}]}
          >
            <Input placeholder="请输入基地编号"/>
          </Form.Item>
          <Form.Item
            name="userRole"
            label="角色"
            rules={[{required: true, message: '请选择角色'}]}
          >
            <Select placeholder="请选择角色">
              <Select.Option value="0">普通用户</Select.Option>
              <Select.Option value="1">管理员</Select.Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title='修改用户角色'
        visible={isRoleModalVisible}
        onCancel={() => setIsRoleModalVisible(false)}
        onOk={async () => {
          await handleSubmitChangeUserRole();
        }}
      >
        <Form form={form} layout='vertical'>
          <Form.Item
            name='userRole'
            label='选择角色'
            rules={[{required: true, message: '请选择一个角色'}]}
          >
            <Select placeholder='请选择角色'>
              <Select.Option value={0}>普通用户</Select.Option>
              <Select.Option value={1}>管理员</Select.Option>
              <Select.Option value={2}>VIP</Select.Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>

  );
};
export default UserManage;
